<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1,user-scalable=yes">
		<title>电子印签签署</title>
		<link rel="stylesheet" href="../css/mui.min.css">
		<link rel="stylesheet" href="../css/lzmui.css">
		<link rel="stylesheet" type="text/css" href="../css/contractSign.css"/>
	</head>
	<body>
		<div id="App" >
			<div class="a-Top">
				<div><button type="button" class="mui-btn mui-btn-warning" :disabled="sealList[pdf.page.pageNum]&&!sealList[pdf.page.pageNum].isUse" @tap="delElectronSeal">清除当前签章</button></div>
				<div>
					<button type="button" class="mui-btn mui-btn-primary" :disabled="pdf.page.pageNum==1" @tap="prevPage">上一页</button>
					<button type="button" class="mui-btn mui-btn-primary" :disabled="pdf.page.total==pdf.page.pageNum" @tap="nextPage">下一页</button>
					<button  type="button" class="mui-btn mui-btn-primary">
						{{pdf.page.pageNum}}/{{pdf.page.total}}
					</button>
				</div>
			</div>
			<!-- 渲染pdf的地方 -->
			<canvas ref="pdfCanvas" id="pdfCanvas" :style="{transform: `scale(${touch.scale})`}"></canvas>
			
			<!-- 渲染印章 -->
			<div class="c-cter" @touchmove="touchmove" @touchstart="touchstart">
				<!-- 渲染自己可拖动的电子章 -->
				<canvas ref="sealCavas" id="sealCavas" ></canvas>
				<!-- 渲染其他签署方签署的印章 -->
				<template v-if="contractInfo&&contractInfo.signedList">
					<div v-for="(item,index) in contractInfo.signedList" :key="index" v-if="item.signContent[pdf.page.pageNum].isUse==true">
						<div class="other-cter" v-for="(sl,si) in item.signContent[pdf.page.pageNum].sealArr" :key="si"  :style="{position:'absolute',left:sl.left+'px',top:sl.top+'px'}">
							<img :src="'data:image/png;base64,'+item.sealImageData" :style="{width: item.signContent[pdf.page.pageNum].width*pdf.scale+'px',height:item.signContent[pdf.page.pageNum].height*pdf.scale+'px'}"/>
						</div>
					</div>
					
				</template>
				<!-- 骑缝章滑块 -->
				<div v-if="paging.checked&&applicationCoveredNum>0" ref="pagingSeal" class="pagingSeal" 
				:style="{top: paging.top  + 'px', left: paging.left  + 'px'}" @touchstart="onButtonDown">
					骑缝章
				</div>
			</div>
			<!-- 底部元素 -->
			<nav class="mui-bar mui-bar-tab">
				<a class="mui-tab-item" href="#tabbar" @tap="navgetTo">
					<span class="mui-tab-label">电子印章</span>
				</a>
				<a class="mui-tab-item" href="#contract-details" @tap="navgetTo">
					<span class="mui-tab-label">合同详情</span>
				</a>
				<a class="mui-tab-item" href="#contract-sign" @tap="navgetTo">
					<span class="mui-tab-label">功能操作</span>
				</a>
			</nav>
			<!-- 可拖拽的电子印章 -->
			<div id="tabbar" class="mui-popover mui-popover-action mui-popover-bottom">
				<div class="tabbar-seal">
					<div class="title">
						<div class="t-title"><span class="mui-icon mui-icon-contact"></span> 我的电子印章</div>
						<span class="t-subtitle">(可拖动至合同上)</span>
					</div>
					<div id="draggable">
					    <div class="drag-item-li" v-for="(item,index) in draggable.list" :key="index" >
					    	<img class="image" :src="item.url" />
					    </div>
					</div>
					<div class="title">
						<div class="t-title"><span class="mui-icon mui-icon-contact"></span> 骑缝章</div>
						<span class="t-subtitle">(合同上必须盖了电子印章才能生效)</span>
					</div>
					<div class="mui-input-row mui-checkbox mui-left" @tap="getValueBtn">
						<input name="骑缝章" :value="paging.checked" type="checkbox" id="pagingSeal">
						<label>骑缝章</label>
					</div>
					<template v-if="paging.checked">
						<div style="display: flex;align-items: center;" @tap="chageRadio">
							<div class="mui-input-row mui-left mui-radio">
								<label>左边</label>
								<input name="radio1" :value="0" type="radio" class="lz-radio" checked>
							</div>
							<div class="mui-input-row mui-left mui-radio">
								<label>右边</label>
								<input name="radio1" :value="$refs.pdfCanvas.style.width.split('px')[0] - 40" type="radio" class="lz-radio">
							</div>
						</div>
					</template>
				</div>
			</div>
			<!-- 合同详情 -->
			<div id="contract-details" class="mui-popover mui-popover-action mui-popover-bottom" v-if="contractInfo">
				<div class="tabbar-details-warp tabbar-seal">
					<div class="title">
						<div class="t-title"><span class="mui-icon mui-icon-settings"></span> 合同详情</div>
						<span class="t-subtitle">(基本信息)</span>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">申请单名称：</div>
						<div class="ul-li-right mui-ellipsis">{{contractInfo.title}}</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">合同编号：</div>
						<div class="ul-li-right">{{contractInfo.serialNumber}}</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">合同状态：</div>
						<div class="ul-li-right mui-ellipsis">{{contractInfo.signStatus}}</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">截止日期：</div>
						<div class="ul-li-right mui-ellipsis">{{contractInfo.expireTime}}</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">创建日期：</div>
						<div class="ul-li-right mui-ellipsis">{{contractInfo.createDate}}</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">加盖次数：</div>
						<div class="ul-li-right mui-ellipsis">{{contractInfo.applicationTotalNum}}</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-left">已盖次数：</div>
						<div class="ul-li-right mui-ellipsis">{{applicationCoveredNum}}</div>
					</div>
					<div class="title">
						<div class="t-title"><span class="mui-icon mui-icon-settings"></span> 签署步骤</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-right mui-ellipsis blue">1. 把印章拖到需要的位置上</div>
					</div>
					<div class="lz-ul-li">
						<div class="ul-li-right mui-ellipsis blue">2. 点击 ‘功能操作’ -->  ‘立即签署’ </div>
					</div>
				</div>
			</div>
			<!-- 签署 -->
			<div id="contract-sign" class="mui-popover">
				<ul class="mui-table-view">
				    <li class="mui-table-view-cell" @tap="oneTouch">一键生成签章</li>
				    <li class="mui-table-view-cell" @tap="delElectronSealAll" style="color: #f0ad4e;">清除所有签章</li>
				    <li class="mui-table-view-cell" @tap="singFn">立即签署</li>
				    <li class="mui-table-view-cell" @tap="preservation">保存</li>
				</ul>
			</div>
			<!-- 发送短信验证码 -->
			<div class="lz-popup" v-if="code.show" :style="{display:code.show==true?'flex':'none'}">
				<div class="popup-center">
					<div class="p-title">印章管理员短信授权</div>
					<div class="p-center p1">
						<input v-model="code.checkCode" type="text" class="mui-input-clear" placeholder="请输入短信验证码" style="margin-bottom: 0;height: 34px;width: 160px;font-size: 12px;">
						<div>
							<button type="button" class="mui-btn mui-btn-primary mui-btn-outlined" style="font-size: 12px;" @tap="sendVerCode">{{code.tips}}</button>
						</div>
					</div>
					<div class="tips" v-if="contractInfo&&contractInfo.transactorUser">
						{{`【验证码】将发送给印章管理员【${contractInfo.transactorUser}】${contractInfo.transactorPhone}`}}
					</div>
					<div class="p-bottom">
						<div class="b-l" @tap="code.show=false">取消</div>
						<div class="b-r" @tap="confirmVerCode">签 署</div>
					</div>
				</div>
			</div>
			<!-- 发送ca证书授权 -->
			<div class="lz-popup" v-if="CA.show" :style="{display:CA.show==true?'flex':'none'}">
				<div class="popup-center">
					<div class="p-title">智能印章设备授权</div>
					<div class="p-center">
						<div class="animated" v-if="CA.animate">
							<img :src="CA.src" />
						</div>
						<div v-else style="width: 100%;">
							<div class="animated" v-if="contractInfo.signStatus=='confirmed'">
								<img :src="CA.src" />
							</div>
							<div v-else>
								<div class="lz-ul-li">
									<div class="ul-li-left">实体章名：</div>
									<div class="ul-li-right mui-ellipsis">{{contractInfo.device}}</div>
								</div>
								<div class="lz-ul-li">
									<div class="ul-li-left">在线状态：</div>
									<div class="ul-li-right mui-ellipsis">{{device.online==true?'在线':'离线'}}</div>
								</div>
								<div class="lz-ul-li">
									<div class="ul-li-left">授权状态：</div>
									<div class="ul-li-right mui-ellipsis">{{contractInfo.signStatus=='confirmed'?'已授权':'未授权'}}</div>
								</div>
								<div class="lz-ul-li" v-if="contractInfo.signStatus!='confirmed'">
									<div class="ul-li-left">请求授权：</div>
									<div class="ul-li-right mui-ellipsis">
										<button type="button" class="mui-btn mui-btn-primary" @tap="applyCaAuthorized" style="padding: 2px 5px;font-size: 12px;">请求授权</button>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="p-bottom">
						<div class="b-l" @tap="closeVerCode">取消</div>
						<button style="flex: 1;" type="button" class="mui-btn mui-btn-primary b-r" :disabled="contractInfo.signStatus!='confirmed'" @tap="sendSingFn">签 署</button>
						
					</div>
				</div>
			</div>
			
		</div>
		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js">
		</script>
		<script type="text/javascript" src="../js/vue.js"></script>
		<script type="text/javascript" src="../js/mui.min.js"></script>
		<script type="text/javascript" src="../js/global.js"></script>
		<!-- 版本选择pdfjs-dist@2.4.456 否则手机端显示不出来 -->
		<script type="text/javascript" src="../js/pdf/pdf.min.js"></script>
		<!-- 渲染canvas -->
		<script type="text/javascript" src="../js/fabric/fabric.min.js"></script>
		<!-- 拖拽的 -->
		<!-- <script src="https://www.itxst.com/package/sortable/sortable.min.js"></script> -->
		<script type="text/javascript" src="../js/sortable/sortable.min.js"></script>
		<script type="text/javascript">
			pdfjsLib.GlobalWorkerOptions.workerSrc = '../js/pdf/pdf.worker.min.js';	
			// 为了解决uni-app 的web-view组件中加载mui开发的H5页面时，点击返回报错Uncaught ReferenceError: mui is not defined at __uniappview.html:1
			mui.init({
				keyEventBind: {
					backbutton: false //关闭back按键监听
				}
			});
			document.addEventListener('UniAppJSBridgeReady', function() {
				
				let that, xhr;
				new Vue({
					el: '#App',
					data: {
						screen:{
							clientWidth:document.documentElement.clientWidth,
							clientHeight:document.documentElement.clientHeight
						},
						pdf: {
							isRendering: false, //是否正在渲染
							pageNumPending: null,
							scale: 1, //渲染内容比例（ 放大倍数）
							url: '',
							doc: null,
							page: {
								pageNum: 1, //当前页数
								total: 0 // 总页数
							}
						},
						// 当前页面渲染的印章电子图片
						sealImage: {
							canvas: null,//当前电子印章画布
						},
						draggable: {
							list: []
						},
						//每个页面的电子章的信息
						sealList:[],
						//获取到的企业合同信息
						contractInfo:null,
						applicationCoveredNum:0,//已盖次数
						//传过来的参数
						webView:{
							//要请求的api
							api:{}
						},
						//验证码
						code:{
							timer:null,
							checkCode:'',
							show:false,
							seconds:60,
							tips: '发送验证码',
						},
						//为了双指缩放
						touch:{
							start:[],//开始手指
							scale:1,//缩放比例
						},
						CA:{
							show:false,
							animate:false,//是否开启动画
							title:'等待印章确认',
							timer:null,//定时器
							src:'../images/seal2.png',
							uuid:'',
						},
						paging:{
							checked:false,//是否选择骑缝章
							flags: false,//拖动开始
							top:0,
							left:0,
							scrollHeight:0,
							position:{
								x:0,
								y:0,
								left:0,
								top:0
							}
						},
						device:{
							timer:null,//定时器
							online:false,//是否在线
						}
					},
					mounted() {
						that = this
						//获取传参数据
						this.getUrlParams()
						//初始化可拖拽原宿
						this.initSortable()
					},
					methods: {
						//获取左右
						chageRadio(){
							setTimeout(()=>{
								let eleArr=document.getElementsByClassName('lz-radio')
								for (var i = 0; i < eleArr.length; i++) {
									if(eleArr[i].checked){
										this.paging.left = eleArr[i].value
									}
								}
							},200)
						},
						//获取是否勾选骑缝章
						getValueBtn(){
							setTimeout(()=>{
								let value=document.getElementById('pagingSeal').checked
								this.paging.checked=value
							},200)
						},
						//定时请求在线状态
						setTime(){
							if(this.device.timer)clearInterval(this.device.timer);
							this.device.timer=setInterval(()=>{
								this.
								findDeviceInfo()
							},5000)
						},
						findDeviceInfo(){
							$lizhao.get(this.webView.api.GLOBAL_device_signet_findDeviceInfo+'/'+this.contractInfo.deviceId, '').then((res) => {
								if (res.code == 200) {
									this.device.online=res.data.online
									//启用定时请求
									that.setTime()
								}else{
									clearInterval(this.device.timer)
								}
							})
						},
						//骑缝章移动
						onButtonDown(event){
							//开始移动
							this.pagingSealMouseDown(event);
							//监听事件
							window.addEventListener('touchmove', this.pagingSealMouseMove);
							window.addEventListener('touchend', this.pagingSealMouseUp);
						},
						pagingSealMouseDown(event){
							this.paging.flags = true
							const refs = this.$refs.pagingSeal.getBoundingClientRect()
							// this.paging.scrollHeight=document.getElementById('lz-dialog-lz').scrollTop
							this.paging.position.x = event.touches[0].clientX
							this.paging.position.y = event.touches[0].clientY
							this.paging.position.left = refs.left
							this.paging.position.top = refs.top
						},
						pagingSealMouseMove(e){
							if(this.paging.flags){
								const xPum = this.paging.position.left + e.touches[0].clientX - this.paging.position.x
								const yPum = this.paging.position.top + e.touches[0].clientY - this.paging.position.y + this.paging.scrollHeight
								this.paging.top= yPum - 50
								this.banOut()
							}
						},
						pagingSealMouseUp(event){
							this.paging.flags = false
							this.banOut()
							window.removeEventListener('touchmove', this.pagingSealMouseMove);
							window.removeEventListener('touchend', this.pagingSealMouseUp);
						},
						//避免拖动出界的限制
						banOut () {
							$lizhao.debounce(()=>{
								const refs = this.$refs.pagingSeal.getBoundingClientRect()
								let height=parseInt(this.$refs.pdfCanvas.style.height)
								if (this.paging.top < 0) {
									this.paging.top = 0
								}else if (this.paging.top > height - refs.height ){
									this.paging.top = height - refs.height
								}
							})
						},
						//启用定时请求
						initTime(){
							if(this.CA.timer)clearInterval(this.CA.timer);
							this.CA.timer=setInterval(()=>{
								//获取印章授权状态
								this.findAuthorized()
							},5000)
						},
						//获取印章授权状态
						findAuthorized(){
							$lizhao.get(this.webView.api.GLOBAL_electronic_enterprise_application_findAuthorized, {enterpriseApplicationId:this.webView.enterpriseApplicationId,uuid:that.CA.uuid}).then((res) => {
								if (res.code == 200) {
									// (ACK回调) 0成功 1失败  2印章正在使用中 3指纹识别超时 4证书不存在
									if(res.data==0){
										that.CA.animate=false
										that.contractInfo.signStatus='confirmed'
										that.CA.src='../images/seal.png'
										clearInterval(that.CA.timer);
									}else if(res.data==1){
										that.CA.animate=false
										mui.toast('失败') 
										that.CA.src='../images/seal2.png'
										clearInterval(that.CA.timer);
									}else if(res.data==2){
										that.CA.animate=false
										mui.toast('印章正在使用中') 
										that.CA.src='../images/seal2.png'
										clearInterval(that.CA.timer);
									}else if(res.data==3){
										that.CA.animate=false
										mui.toast('指纹识别超时') 
										that.CA.src='../images/seal2.png'
										clearInterval(that.CA.timer);
									}else if(res.data==4){
										that.CA.animate=false
										mui.toast('证书不存在') 
										that.CA.src='../images/seal2.png'
										clearInterval(that.CA.timer);
									}
									
								}else{
									clearInterval(that.CA.timer);
								}
							})
						},
						//请求授权
						applyCaAuthorized(){
							that.CA.uuid=''
							//获取印章授权状态
							$lizhao.post(this.webView.api.GLOBAL_electronic_enterprise_application_applyCaAuthorized+'/'+this.webView.enterpriseApplicationId, '').then((res) => {
								if (res.code == 200) {
									that.CA.animate=true
									that.CA.uuid=res.data
									mui.toast(res.msg) 
									//启用定时请求
									that.initTime()
								}else{
									mui.toast(res.msg) 
								}
							})
						},
						//关闭ca授权窗口
						closeVerCode(){
							that.CA.animate=false
							that.CA.show=false
							clearInterval(that.CA.timer);
							clearInterval(that.device.timer);
						},
						touchstart(e){
							 //判断是否有两个点在屏幕上
							if (e.touches.length == 2) {
								this.touch.start = e.touches; //得到第一组两个点
							};
						},
						touchmove(e){
							e.preventDefault();
							if (e.touches.length == 2 ) {
								var now = e.touches;
								let scale= (this.getDistance(now[0], now[1]) / this.getDistance(this.touch.start[0], this.touch.start[1]))
								if(scale<1){
									scale=1
								}
								this.touch.scale = scale;
							}
						},
						//缩放 勾股定理方法
						getDistance(p1, p2) {
							var x = p2.pageX - p1.pageX,
							y = p2.pageY - p1.pageY;
							return Math.sqrt((x * x) + (y * y));
						},
						//获取传参数据
						getUrlParams(){
							this.webView=JSON.parse(decodeURIComponent(GLOBAL_getUrlParam('data')))
							Global_params=JSON.parse(decodeURIComponent(GLOBAL_getUrlParam('data')))
							//console.log('接收到参数',this.webView);
							//请求合同详情
							this.findList()
						},
						//一键生成盖章
						oneTouch(){
							//判断当前页面的电子印章是否存在，如果存在（以当前印章所在位置，一键生成所有页面）
							let index=this.pdf.page.pageNum
							let obj=JSON.parse(JSON.stringify(this.sealList[index]))
							delete obj.index
							if(obj.isUse==true){
								this.sealList = this.sealList.map((item,i)=>{
									if((index<i||index==i)&&(i<index+this.contractInfo.applicationTotalNum)){
										item={
											...item,
											...obj
										}
									}else{
										item.isUse=false
									}
									return item
								})
								let arr= this.sealList.filter(item=>item.isUse==true)
								this.applicationCoveredNum=arr.length
								mui.toast('生成完成')
							}else{
								mui.toast('请指定盖章位置，以便生成') 
							}
						},
						//删除当前页电子章
						delElectronSeal(){
							let index=this.pdf.page.pageNum
							this.$set(this.sealList[index],'isUse',false)
							this.sealList[index].isUse=false
							this.sealList[index].sealArr=[]
							this.sealImage.canvas.clear()
							//设置已盖次数
							this.setPageNum()
						},
						//清空所有签章
						delElectronSealAll(){
							this.sealList = this.sealList.map((item)=>{
								item.isUse=false
								item.sealArr=[]
								return item
							})
							this.applicationCoveredNum=0
							//清空电子章画布
							this.sealImage.canvas.clear()
							mui.toast('清空所有签章完成') 
						},
						// 上一页
						prevPage() {
							if (this.pdf.page.pageNum <= 1) {
								return;
							}
							//清空电子章画布
							this.sealImage.canvas.clear()
							this.pdf.page.pageNum--;
							//预渲染电子印章
							that.renderPage()
						},
						//下一页
						nextPage() {
							if (this.pdf.page.pageNum >= this.pdf.page.total) {
								return;
							}
							//清空电子章画布
							this.sealImage.canvas.clear()
							this.pdf.page.pageNum++;
							//预渲染电子印章
							that.renderPage()
						},
						//初始化可拖拽原宿
						initSortable(e){
							//获取对象
							var el = document.getElementById('draggable');
							//设置配置
							var ops = {
								animation: 1000,
								chosenClass:'chosenClass',//选中拖拽对象的样式,
								onStart: function (evt) {
									that.touch.scale =1
								},
								//拖动结束
								onEnd: function (evt) {
									that.dragEnd(evt,that.draggable.list[evt.newIndex].id)
									mui('#tabbar').popover('toggle')
								}
							};
							//初始化
							var sortable = Sortable.create(el, ops);
						},
						navgetTo(){
							that.touch.scale =1
						},
						//拖拽结束
						dragEnd(e,imageId) {
							if(this.applicationCoveredNum> that.contractInfo.applicationTotalNum||this.applicationCoveredNum== that.contractInfo.applicationTotalNum){
								mui.toast('超出盖章次数') 
								return 
							}else{
								//清空电子章画布
								this.sealImage.canvas.clear()
								let index=this.pdf.page.pageNum
								let X=e.originalEvent.changedTouches[0].clientX
								let Y=e.originalEvent.changedTouches[0].clientY
								let width=this.$refs.pdfCanvas.style.width.split('px')[0]
								let height=this.$refs.pdfCanvas.style.height.split('px')[0]
								// //console.log(X,Y);
								if( X < 0 || Y < 100 || Y > height){
									X =  0 
									Y = 0
								}else if(X>width-100){
									X = width-100
									Y =Y-100
								}else{
									X = X-40
									Y = Y-100
								}
								let obj=this.sealList[index]
								obj.isUse=true
								this.changeSealList(obj,X,Y,imageId)
								//设置已盖次数
								this.setPageNum()
								//渲染印章
								this.renderFabric()
							}
						},
						//设置已盖次数
						setPageNum(){
							let num=0
							this.sealList.forEach(item=>{
								if(item&&item.isUse==true){
									num+=item.sealArr.length
								}
								
							})
							this.applicationCoveredNum=num
						},
						//拖拽电子章结束时改变数组结构
						/**
						 * obj为当前页面信息
						 * left，top为当前电子章的定位信息
						 * imageId：当前电子章的图片url的id，通过这个id可以找到图片url
						 * **/ 
						changeSealList(obj,left,top,imageId){
							obj.sealArr.push({
								aCoords:{//四个点的坐标
									bl:{x:left,y:top+obj.height},
									br:{x:left+obj.width,y:top+obj.height},
									tl:{x:left,y:top},
									tr:{x:left+obj.width,y:top},
								},
								top: top,
								left: left,
								imageId,
								uuid:$lizhao.guid(),//用于拖动改变位置时需要改变对应的数组数据
							})
						},
						// 添加公章
						addSeal() {
							let index=this.pdf.page.pageNum
							let item=this.sealList[index]
							//判断当前页面有没使用电子章，使用了就显示出来
							if(item&&item.isUse==true){
								item.sealArr.forEach((position,sIndex)=>{
									let image=this.draggable.list.find(img=>img.id==position.imageId)
									this.addFabric(item,position,image.url)
								})
							}else{
								//清空电子章画布
								this.sealImage.canvas.clear()
							}
						},
						/**
						 * item为当前页的所有参数，
						 * position为每个章的定位信息
						 * img为当前电子章的图片信息
						 * **/ 
						addFabric(item,position,img,imageId){
							fabric.Image.fromURL(img, (oImg) => {
								oImg.set({
									left: position.left,
									top: position.top,
									scaleX: this.pdf.scale,
									scaleY: this.pdf.scale,
									imageId:position.imageId,
									uuid:position.uuid
								});
								oImg.setControlsVisibility({
								    mt:false, 
								    mb:false, 
								    ml:false,
								    mr:false, 
									tl:false,
									tr:false,
									bl:false,
									br:false,
									mtr:false, 
								})
								//设置图片宽高
								oImg.scaleToWidth(item.width*this.pdf.scale); 
								oImg.scaleToHeight(item.height*this.pdf.scale); 
								this.sealImage.canvas.add(oImg);
							});
						},
						//限制拖动区域（此为对象坐标原点设置在中心的情况）
						checkBoudningBox(e) {
							let index=this.pdf.page.pageNum
							const obj = e.target
							if (!obj) {
								return
							}
							obj.setCoords()
							const objBoundingBox = obj.getBoundingRect()
							//记录数据
							let sealInfo=JSON.parse(JSON.stringify(this.sealList[index]))
							sealInfo.sealArr=sealInfo.sealArr.map(sealItem=>{
								if(sealItem.uuid==obj.uuid){
									sealItem.aCoords=obj.aCoords
									sealItem.left=objBoundingBox.left
									sealItem.top=objBoundingBox.top
									if (objBoundingBox.top < 0) {
										obj.set('top', 0)
										obj.setCoords()
										sealItem.top=0
									}
									if (objBoundingBox.left > this.sealImage.canvas.width - objBoundingBox.width) {
										obj.set('left', this.sealImage.canvas.width - objBoundingBox.width)
										obj.setCoords()
										sealItem.left=this.sealImage.canvas.width - objBoundingBox.width
									}
									if (objBoundingBox.top > this.sealImage.canvas.height - objBoundingBox.height) {
										obj.set('top', this.sealImage.canvas.height - objBoundingBox.height)
										obj.setCoords()
										sealItem.top=this.sealImage.canvas.height - objBoundingBox.height
									}
									if (objBoundingBox.left < 0) {
										obj.set('left', 0)
										obj.setCoords()
										sealItem.left=0
									}
								}
								return sealItem
							})
							this.sealList[index]=sealInfo
							//限制电子印章的放大，最大400px
							if(objBoundingBox.width>400){
								obj.scaleToWidth(400); 
							}
							if(objBoundingBox.height>400){
								obj.scaleToWidth(400); 
							}
						},
						// 生成绘图区域
						renderFabric() {
							//判断当前cavas是否已经创建，创建过则直接绘制印章
							if(this.sealImage.canvas){
								// 添加公章
								this.addSeal()
								return
							}
							let index=this.pdf.page.pageNum
							let pdfCanvas = this.$refs.pdfCanvas;
							let sealCavas = this.$refs.sealCavas;
							sealCavas.height = parseInt(pdfCanvas.style.height); //返回内容高度
							sealCavas.width =  parseInt(pdfCanvas.style.width); //返回内容宽度
							// selection防止在fabricjs中拖动多重选择{selection: false}
							this.sealImage.canvas = new fabric.Canvas(sealCavas,{selection: false});
							//监听旋转拖动和放大，限制可拖动的区域
							this.sealImage.canvas.on('object:moving', function(e) {
								that.touch.scale =1
								that.checkBoudningBox(e)
							})
							this.sealImage.canvas.on('object:rotating', function(e) {
								that.checkBoudningBox(e)
							})
							this.sealImage.canvas.on('object:scaling', function(e) {
								that.checkBoudningBox(e)
							})
							// 添加公章
							this.addSeal()
						},
						//处理服务端返回数据
						processingData(){
							//判断用户有没有保存过电子印章，如果有则显示之前保存的，如果没有则生成
							if(this.contractInfo&&this.contractInfo.signContent){
								this.sealList=JSON.parse(this.contractInfo.signContent)
								//把pc的坐标放大系数1转换为手机端的放大系数再显示
								let arr= this.sealList.filter((item,index)=>{
									if(item.isUse==true&&index!=0){
										item.sealArr.forEach(seal=>{
											seal.aCoords.bl.x=seal.aCoords.bl.x*item.scale
											seal.aCoords.bl.y=seal.aCoords.bl.y*item.scale
											seal.aCoords.br.x=seal.aCoords.bl.x*item.scale
											seal.aCoords.br.y=seal.aCoords.br.y*item.scale
											seal.aCoords.tl.x=seal.aCoords.tl.x*item.scale
											seal.aCoords.tl.y=seal.aCoords.tl.y*item.scale
											seal.aCoords.tr.x=seal.aCoords.tr.x*item.scale
											seal.aCoords.tr.y=seal.aCoords.tr.y*item.scale
											seal.left=seal.left*this.pdf.scale
											seal.top=seal.top*this.pdf.scale
										})
										return item
									}
								})
								this.applicationCoveredNum=arr.length
							}else{
								//初始化每个页都生成一个虚拟电子章
								this.setElectronicSeal()
							}
						},
						//初始化每个页都生成一个虚拟电子章
						setElectronicSeal(){
							let arr=[]
							for (var i = 0; i < this.pdf.page.total+1; i++) {
								arr.push({
									index:i,
									isUse:false,//当前页面是否盖章了
									width: 150,//电子章的宽高
									height: 150,
									scale:this.pdf.scale,
									sealArr:[],//当前页面盖的电子章数量位置
								})
							}
							this.sealList=arr
						},
						// 初始化pdf
						initPdf() {
							mui.showLoading('数据正在加载中...')
							pdfjsLib.getDocument(this.pdf.url).promise.then((pdfDoc_) => {
								this.isLoading = false;
								// 返回pdf实例 getDocument
								this.pdf.doc = pdfDoc_;
								// 返回总页数
								this.pdf.page.total = this.pdf.doc.numPages;
								this.pdf.page.pageNum = 1;
								//渲染pdf
								this.renderPage('init');
							}).catch((err) => {
								//console.log(err);
								mui.hideLoading()
								mui.toast('加载失败，稍后重试') 
							});
						},
						// 渲染pdf
						renderPage(type) {
							//正在渲染
							this.pdf.isRendering = true;
							let canvas = this.$refs.pdfCanvas;
							this.pdf.doc.getPage(this.pdf.page.pageNum).then((page) => {
								mui.hideLoading()
								// 返回页面内容(比例) page.getViewport(scale)
								let ctx = canvas.getContext("2d")
								this.pdf.scale=this.screen.clientWidth/page.getViewport({scale:1}).width
								if(type=='init'){
									//处理服务端返回数据(判断用户有没有保存过电子印章，如果有则显示之前保存的，如果没有则生成)
									this.processingData()
								}
								var viewport = page.getViewport({scale:this.pdf.scale});
								//作者李钊在写这个pdf时，有个问题：手机上渲染出来的Pdf不高清，主要是dpi 的原因 默认dpi为96，然后网页一般使用dpi为72。
								//解决手机端不高清的问题
								let dpr = window.devicePixelRatio || 1;
								let bsr =ctx.webkitBackingStorePixelRatio ||ctx.mozBackingStorePixelRatio ||ctx.msBackingStorePixelRatio ||
									ctx.oBackingStorePixelRatio ||ctx.backingStorePixelRatio ||1;
								let ratio = dpr / bsr;
								canvas.width = this.screen.clientWidth * ratio;
								canvas.height = viewport.height * ratio;
								canvas.style.width = this.screen.clientWidth + "px";
								canvas.style.height = viewport.height + "px";
								ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
								//
								//解决结束
								var renderContext = {
									canvasContext: ctx, //画布
									viewport: viewport, //内容
								};
								// 页面呈现({画布,内容}) page.render(renderContext);
								var renderTask = page.render(renderContext);
								renderTask.promise.then(() => {
									//预渲染电子印章
									that.renderFabric()
									this.pdf.isRendering = false;
								});
							});
						},
						// 获取企业合同详情
						findList() {
							$lizhao.get(this.webView.api.GLOBAL_electronic_enterprise_contract_find+'/'+this.webView.enterpriseApplicationId, '').then((res) => {
								if (res.code == 200 && res.data) {
									if(res.data.signedList){
										res.data.signedList.forEach(item=>{
											item.signContent=JSON.parse(item.signContent)
										})
									}
									this.contractInfo=res.data
									this.applicationCoveredNum=0//已盖次数默认值为0
									//电子章图片
									this.draggable.list=[{url:'data:image/png;base64,'+res.data.sealImageData,id:res.data.id}],
									//合同pdf
									this.pdf.url=res.data.fileEntity.fileUrl+'?Authorization='+that.webView.token+'&us=app'
									// 初始化pdf
									this.initPdf()
								}else{
									this.contractInfo=null
									this.pdf.url=''
									this.draggable.list=[]
									mui.toast(res.msg) 
								}
							})
						},
						//倒计时
						getCode(){
							if (!this.code.timer) {
								this.code.timer = setInterval(() => {
									if (this.code.seconds > 0) {
										this.code.seconds--;
										this.code.tips=this.code.seconds+'秒后重新获取'
									} else {
										this.code.seconds=60
										clearInterval(this.code.timer);
										this.code.timer = null;
										this.code.tips='重新获取'
									}
								}, 1000)
							}
						},
						//发送验证码
						sendVerCode(){
							if(this.code.seconds==60) {
								$lizhao.post(this.webView.api.GLOBAL_electronic_message_authenticationCode_sendSMSAuthenticationCode+'/'+this.webView.enterpriseApplicationId, '').then((res) => {
									if (res.code == 200) {
										// 倒计时
										that.getCode()
										mui.toast(res.msg) 
									}else{
										mui.toast(res.msg) 
									}
								})
							}else{
								mui.toast('倒计时结束后再发送') 
							}
						},
						//确定验证码
						confirmVerCode(){
							if(!this.code.checkCode){
								mui.toast('请填写验证码') 
								return
							}
							let codeReq={
								checkCode: this.code.checkCode,
								enterpriseApplicationId: this.webView.enterpriseApplicationId
							}
							$lizhao.post(this.webView.api.GLOBAL_electronic_message_authenticationCode_verifySMSAuthenticationCode, codeReq).then((res) => {
								if (res.code == 200) {
									//发送签署
									that.sendSingFn()
								}else{
									mui.toast(res.msg)
								}
							})
						},
						//发送签署
						sendSingFn(){
							//过滤出哪些页面盖了电子章,由于后台需要的坐标是整数所以Math.floor
							let seal1=JSON.parse(JSON.stringify(this.sealList))
							let arr=[]
							seal1.forEach(item=>{
								if(item&&item.isUse==true&&item.index!=0){
									item.sealArr.forEach(sl=>{
										let obj={
											signLocationLBX:Math.floor(sl.aCoords.bl.x/item.scale),
											signLocationLBY:Math.floor(sl.aCoords.bl.y/item.scale),
											signLocationRUX:Math.floor(sl.aCoords.tr.x/item.scale),
											signLocationRUY:Math.floor(sl.aCoords.tr.y/item.scale),
											signOnPage:item.index
										}
										arr.push(obj)
									})
								}
							})
							//获取pdf高度
							let height = parseInt(this.$refs.pdfCanvas.style.height)/this.pdf.scale
							let width = parseInt(this.$refs.pdfCanvas.style.width)/this.pdf.scale
							
							let req={
								authorizationTime:$lizhao.timeFormat(new Date().getTime()) ,//授权时间,用户输入验证码的时间
								enterpriseApplicationId:this.webView.enterpriseApplicationId,//企业合同id
								signLocations:arr,
								signContent:JSON.stringify(this.sealList),
								signTotal:parseInt(this.applicationCoveredNum),
								width:width,
								height:height,
							}
							//骑缝章
							if(this.paging.checked&&this.applicationCoveredNum>0){
								req.crossPage={
									crossPageStyle:this.paging.left==0 ? 1 : 2,
									offsetCoordY:height - this.paging.top/this.pdf.scale - 150
								}
							}
							$lizhao.post(this.webView.api.GLOBAL_owner_application_sign, req).then((res) => {
								if (res.code == 200 ) {
									that.code.show=false
									that.CA.show=false
									mui.toast(res.msg)
									setTimeout(()=>{
										uni.navigateBack({
										    delta: 1
										});
									},1500)
								}else{
									mui.toast(res.msg)
								}
							})
						},
						//签署
						singFn(){
							//过滤出哪些页面盖了电子章
							let arr= this.sealList.filter(item=>item.isUse==true)
							if(arr&&arr.length>0){
								mui('#contract-sign').popover('toggle')
								if(this.contractInfo.authorizeType=='ca'){
									//如果授权人选择了CA验证，则需要下发指令给实体章确认，
									if(this.contractInfo.signStatus=='confirmed'){
										//发送签署
										that.sendSingFn()
									}else{
										this.CA.show=true
										//获取在线状态
										this.findDeviceInfo()
									}
								}else if(this.contractInfo.authorizeType=='sms'){
									//如果是短信sms，则需要经办人验证码 confirmed代表已经授权
									if(this.contractInfo.signStatus=='confirmed'){
										//发送签署
										that.sendSingFn()
									}else{
										this.code.show=true
									}
									
								}
								
							}else{
								mui.toast('请先加盖电子印章') 
							}
						},
						//保存
						preservation(){
							//过滤出哪些页面盖了电子章(处理下放大系数，否则pc端显示有问题)
							let arr= this.sealList.filter(item=>{
								if(item&&item.isUse==true){
									item.sealArr.forEach(se=>{
										se.left=se.left/item.scale
										se.top=se.top/item.scale
										se.aCoords.bl.x=se.aCoords.bl.x/item.scale
										se.aCoords.bl.y=se.aCoords.bl.y/item.scale
										se.aCoords.br.x=se.aCoords.bl.x/item.scale
										se.aCoords.br.y=se.aCoords.br.y/item.scale
										se.aCoords.tl.x=se.aCoords.tl.x/item.scale
										se.aCoords.tl.y=se.aCoords.tl.y/item.scale
										se.aCoords.tr.x=se.aCoords.tr.x/item.scale
										se.aCoords.tr.y=se.aCoords.tr.y/item.scale
									})
									return item
								}
							})
							if(arr&&arr.length>0){
								let req={
									enterpriseApplicationId:this.webView.enterpriseApplicationId,
									signContent:JSON.stringify(this.sealList)
								}
								$lizhao.post(this.webView.api.GLOBAL_electronic_enterprise_contract_save, req).then((res) => {
									if (res.code == 200) {
										mui.toast(res.msg) 
									}
								})
							}else{
								mui.toast('请先加盖电子印章') 
							}
							
						},
					}
				})
			});
		</script>
	</body>
</html>
